//
//  WHExpressInController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/2.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHExpressInController.h"
#import "WHTextInfoCell.h"
#import "WHTransNumberCell.h"
#import "WHExpressInfoCell.h"
#import "WHExpressSelectView.h"
#import "WHScanController.h"
#import "WHRootNavigationController.h"
#import "WHMsgChargeController.h"
#import "WHExpressModel.h"

@interface WHExpressInController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;

@property (nonatomic, copy) NSString *expressName; // 快递名称
//@property (nonatomic, copy) NSString *courierName; // 快递员名称
@property (nonatomic, strong) WHDeliverModel *deliverModel; // 快递员

@property (nonatomic, copy) NSString *exressNumber; // 运单号
@property (nonatomic, copy) NSString *receivePhone; // 收件人电话

@property (nonatomic, strong) UILabel *desLabel;

@end

@implementation WHExpressInController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"快递入库";
    
    [self setUpExpressInUI];
}

- (void)setUpExpressInUI {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHExpressInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHExpressInfoCell class])];
    [dataTableView registerClass:[WHTextInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHTextInfoCell class])];
    [dataTableView registerClass:[WHTransNumberCell class] forCellReuseIdentifier:NSStringFromClass([WHTransNumberCell class])];

    dataTableView.tableFooterView = [self tableFooterView];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    dataTableView.separatorColor = CLineColor;
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
    }];
    
    _dataTableView = dataTableView;
}

- (UIView *)tableHeaderView {
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(33));
    
    UIView *desBackView = [[UIView alloc] init];
    desBackView.backgroundColor = HexColor(@"ffeae5");
    [tableHeaderView addSubview:desBackView];
    [desBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(tableHeaderView);
    }];
    
    UILabel *desLabel = [[UILabel alloc] init];
    desLabel.backgroundColor = HexColor(@"ffeae5");
    desLabel.textColor = CMDarkOrangeColor;
    desLabel.font = SYSTEMFONT(kRealwidth(12));
    [desBackView addSubview:desLabel];
    [desLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(desBackView.mas_left).offset(kRealwidth(15));
        make.right.mas_equalTo(desBackView.mas_right).offset(-kRealwidth(15));
        make.top.bottom.mas_equalTo(desBackView);
    }];
    _desLabel = desLabel;
    
    return tableHeaderView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(85));
    
    UIView *gapView = [[UIView alloc] init];
    [tableFooterView addSubview:gapView];
    gapView.backgroundColor = CLineColor;
    gapView.frame = CGRectMake(0, 0, KScreenWidth, 0.5);
    
    UIButton *resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:resetBtn];
    [resetBtn setBackgroundImage:[UIImage imageWithColor:HexColor(@"525f66")] forState:UIControlStateNormal];
    CGFloat buttonWidth = (KScreenWidth-3*KNormalSpace)/2;
    resetBtn.frame = CGRectMake(KNormalSpace, kRealwidth(20), buttonWidth, kRealwidth(45));
    NSString *resetStr = @"重置";
    NSAttributedString *resetAttributeStr = [[NSAttributedString alloc] initWithString:resetStr attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [resetBtn setAttributedTitle:resetAttributeStr forState:UIControlStateNormal];
    [resetBtn addTarget:self action:@selector(reset:) forControlEvents:UIControlEventTouchUpInside];
    ViewRadius(resetBtn, kRealwidth(45)/2);
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:submitButton];
    [submitButton setBackgroundImage:[UIImage imageWithColor:CMDarkOrangeColor] forState:UIControlStateNormal];
    submitButton.frame = CGRectMake(resetBtn.right+KNormalSpace, kRealwidth(20), buttonWidth, kRealwidth(45));
    NSString *submitStr = @"确定入库";
    NSAttributedString *submitAttributeStr = [[NSAttributedString alloc] initWithString:submitStr attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [submitButton setAttributedTitle:submitAttributeStr forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    ViewRadius(submitButton, kRealwidth(45)/2);
    
    return tableFooterView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.row == 0) {
        WHExpressInfoCell *expressInfoCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHExpressInfoCell class]) forIndexPath:indexPath];
        if (self.expressName) {
            expressInfoCell.expressNameLabel.text = self.expressName;
        } else {
            expressInfoCell.expressNameLabel.text = @"请选择快递和快递员";
        }
        
        if (self.deliverModel) {
//            _desBackView.hidden = NO;
            expressInfoCell.courierLabel.text = self.deliverModel.expressName;
        } else {
            expressInfoCell.courierLabel.text = @"";
        }
        
        cell = expressInfoCell;
    } else if (indexPath.row == 1) {
        WHTransNumberCell *numberCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHTransNumberCell class]) forIndexPath:indexPath];
        numberCell.inputTextField.placeholder = @"运单号";
        numberCell.inputTextField.text = self.exressNumber;
        kWeakSelf(self);
        numberCell.textChangeBlock = ^(NSString *text) {
            weakself.exressNumber = text;
        };
        numberCell.beginScan = ^{
            [weakself beginScan];
        };
        numberCell.inputTextField.keyboardType = UIKeyboardTypeDefault;
        cell = numberCell;
    } else if (indexPath.row == 2) {
        WHTextInfoCell *infoCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHTextInfoCell class]) forIndexPath:indexPath];
        
        infoCell.inputTextField.placeholder = @"收件人电话";
        infoCell.inputTextField.text = self.receivePhone;
        kWeakSelf(self);
        infoCell.textChangeBlock = ^(NSString *text) {
            weakself.receivePhone = text;
        };
        infoCell.validType = ValideTypePhoneNumber;
        infoCell.inputTextField.keyboardType = UIKeyboardTypeDefault;
        
        cell = infoCell;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self.view endEditing:YES];
        
        [self selectExpressInfo];
    }
}


#pragma mark - —————— 事件 ——————
- (void)selectExpressBy:(NSArray *)dataArray headerTitle:(NSString *)headerTitle bottomTitle:(NSString *)bottomTitle selectExpress:(selectExpress)select {
    WHExpressSelectView *expressSelectView = [[WHExpressSelectView alloc] initWithArray:dataArray headerTitle:headerTitle bottomTitle:bottomTitle];
    [expressSelectView show];
    expressSelectView.selectExpress = select;
}

- (void)beginScan {
    [self.view endEditing:YES];
    WHScanController *scan = [[WHScanController alloc] init];
    WHRootNavigationController *navi = [[WHRootNavigationController alloc] initWithRootViewController:scan];
    [self presentViewController:navi animated:YES completion:nil];
    kWeakSelf(self);
    scan.outPutStr = ^(NSString *dataStr) {
        [weakself gridOutputStr:dataStr];
    };
}


- (void)reset:(UIButton *)button {
    self.exressNumber = nil;
    self.receivePhone = nil;
    [self.dataTableView reloadData];
}

- (void)submit:(UIButton *)button {
    [self.view endEditing:YES];
    if (!self.expressName || !self.deliverModel) {
        [WHView showAlertwithTitle:nil message:@"请先选择快递和快递员!" okAction:^(UIAlertAction *action) {
            [self selectExpressInfo];
        } cancelAction:nil];
        
        return;
    }
    if (self.exressNumber.length < 5) {
        [WHView showAlertwithTitle:nil message:@"请填写运单号!"];
        
        return;
    }
    
    if (self.receivePhone.length != 11) {
        [WHView showAlertwithTitle:nil message:@"请填写正确的手机号!"];
        
        return;
    }
    
    [self expressInto];
}

#pragma mark - —————— 处理扫描结果 ——————

- (void)gridOutputStr:(NSString *)dataStr {
    
    if ([self isBarCode:dataStr]) {
        self.exressNumber = dataStr;
        [self.dataTableView reloadData];
        
        return;
    }
    [WHView showAlertwithTitle:nil message:@"无法识别!" okAction:nil cancelAction:nil];
}

- (BOOL)isBarCode:(NSString *)checkedNumString {
    NSString *barCodeRegex = @"^[a-zA-Z0-9]+$";
    NSPredicate *barCodePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", barCodeRegex];
    return [barCodePredicate evaluateWithObject:checkedNumString];
}

- (void)showChargeAlert {
    [WHView showAlertwithTitle:@"短信套餐不足10条" message:@"短信不足会造成入库失败,请尽快充值" okTitle:@"充值" okAction:^(UIAlertAction *action) {
        WHMsgChargeController *charge = [[WHMsgChargeController alloc] init];
        [self.navigationController pushViewController:charge animated:YES];
    } cacelTitle:@"取消" cancelAction:nil];
}

#pragma mark - —————— 接口 ——————
- (void)selectExpressInfo {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_clickExpressInto);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          nil];
    
    kWeakSelf(self);
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                NSNumber *stationSurplus = retDict[@"stationSurplus"];
                
                if (stationSurplus.intValue < 10) {
                    [self showChargeAlert];
                }
                
                NSArray *params = retDict[@"params"];
                
                NSMutableArray *expressNameArray = @[].mutableCopy;
                NSMutableArray *expressArray = @[].mutableCopy;
                for (NSDictionary *expressDict in params) {
                    WHExpressModel *expressModel = [WHExpressModel modelWithJSON:expressDict];
                    [expressNameArray addObject:expressModel.expressName];
                    [expressArray addObject:expressModel];
                }
                
                [weakself selectExpressBy:expressNameArray headerTitle:@"请选择快递" bottomTitle:@"下一步" selectExpress:^(NSInteger selectIndex) {
                    weakself.expressName = expressNameArray[selectIndex];
                    
                    WHExpressModel *expressModel = expressArray[selectIndex];
                    
                    NSMutableArray *deliverNameArray = @[].mutableCopy;
                    for (WHDeliverModel *deliverModel in expressModel.data) {
                        [deliverNameArray addObject:deliverModel.expressName];
                    }
                    
                    [weakself selectExpressBy:deliverNameArray headerTitle:@"请选择快递员" bottomTitle:@"完成" selectExpress:^(NSInteger selectIndex) {
                        WHDeliverModel *deliverModel = expressModel.data[selectIndex];
                        weakself.deliverModel = deliverModel;
                        
                        weakself.dataTableView.tableHeaderView = [weakself tableHeaderView];
                        weakself.desLabel.text = NSStringFormat(@"结算员余额%@,还可以录入%@件", weakself.deliverModel.balance, weakself.deliverModel.residue);
                        
                        [weakself.dataTableView reloadData];
                    }];
                }];
                
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)expressInto {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_expressInto);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          self.deliverModel.expressUserId, @"expressUserId",
                          self.exressNumber, @"waybillNum",
                          self.receivePhone, @"mobile",
                          self.expressName, @"expressCompany",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                [WHView showAlertwithTitle:@"入库成功" message:NSStringFormat(@"取件码%@", retDict[@"takeCode"])];
                self.deliverModel.balance = retDict[@"balance"];
                self.deliverModel.residue = retDict[@"residue"];
                
                _desLabel.text = NSStringFormat(@"结算员余额%@,还可以录入%@件", self.deliverModel.balance, self.deliverModel.residue);
                
                [self reset:nil];
                
                if ([kUserDefaults boolForKey:OutVoice]) {
                    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ExpressInto.wav" withExtension:nil];
                    SystemSoundID soundID = 8789;
                    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
                    AudioServicesPlayAlertSound(soundID);
                }
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

@end

